<?php
class AirTime
{
	/*
	 * check to see if it is a valid time string in the format required by SOAP
	 */
	public static function isValidTimeString($timeString)
	{
		$timeString = AirTime::cleanupInputString($timeString);
		$pattern = '/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.?\d*$/';
		//Example of this pattern: 1234-67-90 23:56:89
		return (FALSE != strtotime($timeString))  && preg_match($pattern,$timeString);
	}
	
	/*
	 * return true if the given time string is recent as defined by the local system.
	 */
	public static function isRecentTimeString($timeString)
	{
		date_default_timezone_set('UTC');
		$timeString = AirTime::cleanUpInputString($timeString);
		if (AirTime::isValidTimeString($timeString))
		{
			$futureTimeSecondsToPermit = -2;
			$secondsDefiningRecent = 150;
			$timeDelta = (strtotime(date('Y-m-d H:i:s', time())) - strtotime($timeString));
			$result = (($timeDelta > $futureTimeSecondsToPermit) && ($timeDelta < $secondsDefiningRecent));
		}
		else
		{
			$result = FALSE;
		}
		return $result;
	}

	/*
	 * Remove T and Z from input string to enable SQL to interpret them
	 */
	public static function cleanUpInputString($timeString)
	{
		$sampleString = '1234-67-90 23:56:89';
		$timeString = substr($timeString, 0, strlen($sampleString));
		$result = str_replace('T', ' ', $timeString);
		return $result;
	}

	/*
	 * Convert the MySql format to a time format to return in all interface operations.
	 * YYYY-MM-DDTHH:mm:ss.
	 */
        // TODO this function is unused... remove?
	public static function toGregorianCalendar($timeString)
	{
		$result = str_replace( ' ', 'T', $timeString);
		$pattern = '/:\d{2}$/';
		if (preg_match($pattern,$timeString))
		{
			$result = $result . ".000";
		}
		if (strstr($result, 'Z') == FALSE )
		{
			return $result . 'Z';
		}
		else
		{
			return $result;
		}
	}
}
?>